package com.alibaba.citrus.cr.unified.inventory.facade.service;

import com.alibaba.citrus.cr.unified.inventory.repository.AllocateRelationReadRepository;
import com.alibaba.citrus.cr.unified.inventory.utils.InfoUtil;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.cz.base.tool.page.PageResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcorder.model.dto.GetLoginEmployeeInfoResponse;
import com.epoch.app.bcorder.model.dto.OrganizationSDO;
import com.epoch.app.bcorder.service.BaseDataService;
import com.epoch.app.crplatformenhance.model.dto.GetDownOrganizationListRequest;
import com.epoch.app.crplatformenhance.model.dto.GetDownQueryOrganizationSelectRequest;
import com.epoch.app.crplatformenhance.model.dto.GetDownQueryOrganizationSelectResponse;
import com.epoch.app.crplatformenhance.service.CrPlatformEnhanceService;
import com.epoch.app.crunifiedinventory.api.allocaterelationread.dto.QueryAllocateRelationForOrderRequest;
import com.epoch.app.crunifiedinventory.api.allocaterelationread.service.AllocateRelationReadService;
import com.epoch.app.crunifiedinventory.dto.request.QueryAllocateRelationRequest;
import com.epoch.app.crunifiedinventory.model.dto.WmsSDO;
import com.epoch.app.crunifiedinventory.sdo.AllocateRelationSDO;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author wangcheng
 * @date 2021/10/12
 */
@Service
@Primary
public class AllocateRelationReadServiceImpl implements AllocateRelationReadService {
    private Log log = Log.getLogger(AllocateRelationReadServiceImpl.class);

    @Resource
    AllocateRelationReadRepository allocateRelationReadRepository;
    @Resource
    BaseDataService baseDataService;
    @Resource
    CrPlatformEnhanceService crPlatformEnhanceService;

    //销售组织层级 104
    private static final Integer SALES_ORG_TYPE = 104;

    @Override
    public Result<List<AllocateRelationSDO>> pageQueryAllocateRelation(
        QueryAllocateRelationRequest queryAllocateRelationRequest) {
        AllocateRelationSDO allocateRelationSDO = queryAllocateRelationRequest.getAllocateRelationSDO();
        GetLoginEmployeeInfoResponse loginEmployeeInfo = baseDataService.getLoginEmployeeInfo();
        log.info("AllocateRelationReadServiceImpl_pageQueryAllocateRelation_getLoginEmployeeInfo:{}", JSON.toJSONString(loginEmployeeInfo));
        if (loginEmployeeInfo != null){
            if (loginEmployeeInfo.getOrganizationSDO() != null){
                Integer type = loginEmployeeInfo.getOrganizationSDO().getType();
                OrganizationSDO organizationSDO = loginEmployeeInfo.getOrganizationSDO();
                /**
                 * GROUP(100, "蒙牛集团"),
                 //                 *     ENTERPRISE_GROUP(101, "事业部"),
                 //                 *     REGION(102, "销售大区"),
                 //                 *     COMPANY(103, "分子公司"),
                 //                 *     SALES_ORGANIZATION(104, "销售组织"),
                 //                 *     SALES_CHANNEL(105, "销售渠道"),
                 //                *     SALES_DEPARTMENT(106, "销售部门");
                 //                 */
                if (Objects.equals(type,100) || Objects.equals(type,101)){
                    //角色权限暂定
                }
                if (Objects.isNull(type) || type > 104){
                    return Result.listEmptySuccess();
                }
                //分子公司
                if (Objects.equals(type,103)){
                    //找寻分子公司的下一层级销售组织 取第一个
                    GetDownOrganizationListRequest downOrganizationListRequest = new GetDownOrganizationListRequest();
                    downOrganizationListRequest.setType(SALES_ORG_TYPE);
                    downOrganizationListRequest.setId(organizationSDO.getId());
                    Result<List<com.epoch.app.crplatformenhance.sdo.OrganizationSDO>> downOrganizationList = crPlatformEnhanceService.getDownOrganizationList(downOrganizationListRequest);
                    log.info("AllocateRelationReadServiceImpl_pageQueryAllocateRelation_getDownOrganizationList:{}",JSON.toJSONString(downOrganizationList));
                    if (downOrganizationList != null && CollectionUtils.isNotEmpty(downOrganizationList.getResult())){
                        List<String> orgIds = downOrganizationList.getResult().stream().filter(x -> Objects.equals(x.getType(), SALES_ORG_TYPE)).map(com.epoch.app.crplatformenhance.sdo.OrganizationSDO::getId).collect(Collectors.toList());
                        if (CollectionUtils.isNotEmpty(orgIds)){
                            allocateRelationSDO.setOrganizationCodes(orgIds);
                        }
//                        com.epoch.app.crplatformenhance.sdo.OrganizationSDO sdo = downOrganizationList.getResult().stream().filter(x -> Objects.equals(x.getType(), SALES_ORG_TYPE)).findFirst().orElse(null);
//                        if (sdo != null && StringUtils.isNotBlank(sdo.getId())){
//                            allocateRelationSDO.setOrganizationCode(sdo.getId());
//                        }
                    }
                }
                //销售组织
                if (Objects.equals(type,104)){
//                    allocateRelationSDO.setOrganizationCode(organizationSDO.getId());
                    allocateRelationSDO.setOrganizationCodes(Lists.newArrayList(organizationSDO.getId()));
                }
            }
        }
        log.info("AllocateRelationReadServiceImpl_pageQueryAllocateRelation_allocateRelationSDO:{}",JSON.toJSONString(allocateRelationSDO));
        PageResult<List<AllocateRelationSDO>> allocateRelationaList = allocateRelationReadRepository.queryPageList(allocateRelationSDO);
        if (allocateRelationaList!=null && CollectionUtils.isNotEmpty(allocateRelationaList.getContent())) {
            //处理仓库id 和编码的转换
            List<String> ids = allocateRelationaList.getContent().stream().filter(Objects::nonNull)
                    .flatMap(x -> Stream.of(x.getWareHouseCode(), x.getReceiveWareHouseCode()))
                    .filter(Objects::nonNull)
                    .filter(y -> StringUtils.isNotBlank(y))
                    .distinct().collect(Collectors.toList());
            Map<String, WmsSDO> wmsMap = Maps.newHashMap();
            if (CollectionUtils.isNotEmpty(ids)){
                wmsMap = InfoUtil.getWmsMap(ids);
            }
            for (AllocateRelationSDO sdo : allocateRelationaList.getContent()) {
                WmsSDO wmsSDO = wmsMap.get(sdo.getWareHouseCode());
                WmsSDO receiveWmsSDO = wmsMap.get(sdo.getReceiveWareHouseCode());
                if (wmsSDO != null){
                    sdo.setShipAreaCode(wmsSDO.getCode());
                }
                if (receiveWmsSDO != null){
                    sdo.setReceiveAreaCode(receiveWmsSDO.getCode());
                }
//                sdo.setWareHouseCode(wmsMap.get(sdo.getWareHouseCode()));
            }
//            return Result.listSuccess(allocateRelationaList.getContent(), allocateRelationaList.getContent().size());
            return Result.listSuccess(allocateRelationaList.getContent(), allocateRelationaList.getTotal());
        }
        return Result.listEmptySuccess();
    }
    @Override
    public Result<AllocateRelationSDO> pageQueryAllocateRelationDetails(
            QueryAllocateRelationRequest queryAllocateRelationRequest) {
        AllocateRelationSDO allocateRelationSDO = queryAllocateRelationRequest.getAllocateRelationSDO();
        PageResult<List<AllocateRelationSDO>> allocateRelationaList = allocateRelationReadRepository.queryPageList(allocateRelationSDO);
        List<AllocateRelationSDO> content = allocateRelationaList.getContent();
        if(CollectionUtils.isEmpty(content)){
            return null;
        }
        return Result.success(content.get(0));
    }

    @Override
    public Result<List<AllocateRelationSDO>> queryAllocateRelationForOrder(QueryAllocateRelationForOrderRequest queryAllocateRelationForOrderRequest) {
        PageResult<List<AllocateRelationSDO>> result = null;
        AllocateRelationSDO allocateRelationSDO = new AllocateRelationSDO();
        allocateRelationSDO.setIsEnable(true);
        allocateRelationSDO.setStart(0);
        allocateRelationSDO.setLimit(1);
        //优先根据销售组织+客户查询收发货仓
        allocateRelationSDO.setAddressCode(queryAllocateRelationForOrderRequest.getAddressCode());
        allocateRelationSDO.setOrganizationCode(queryAllocateRelationForOrderRequest.getOrganizationCode());
        result = allocateRelationReadRepository.queryPageList(allocateRelationSDO);
        if (result!=null && CollectionUtils.isNotEmpty(result.getContent())){
            return Result.listSuccess(result.getContent(), result.getContent().size());
        }
        //若无法找到根据销售组织+销售渠道+销售部门查找发货仓
        allocateRelationSDO.setAddressCode("");
        allocateRelationSDO.setSaleChannelCode(queryAllocateRelationForOrderRequest.getSaleChannelCode());
        allocateRelationSDO.setDepartmentCode(queryAllocateRelationForOrderRequest.getSaleDepartmentCode());
        result = allocateRelationReadRepository.queryPageList(allocateRelationSDO);
        if (result!=null && CollectionUtils.isNotEmpty(result.getContent())){
            return Result.listSuccess(result.getContent(), result.getContent().size());
        }
        return Result.listEmptySuccess();
    }
}
